package com.shrfid.rfidsdk.uitls;

import com.shrfid.module_base.util.ByteUtils;

public class TagUtils {

    /**
     * 6bit 压缩解压数据
     *
     * @param source
     * @return
     */
    public static String unzip6bitData(String source) {
        byte[] hexArray = ByteUtils.hexString2Bytes(source);
        String binStr = ByteUtils.byteArrToBinStr(hexArray);
        int start = 0;
        int end = 6;
        String temp = "";
        StringBuffer buffer = new StringBuffer();

        int count = source.length() * 4 / 6;
        for (int i = 0; i < count; i++) {
            temp = binStr.substring(start, end);
            start += 6;
            end += 6;

            if (temp.startsWith("1")) {
                temp = "00" + temp;
            } else if (temp.startsWith("0")) {
                temp = "01" + temp;
            }
            buffer.append(temp);
        }
        String bufferStr = buffer.toString();
        int len = bufferStr.length() / 8;
        byte[] resultArr = new byte[len];
        start = 0;
        end = 8;
        for (int i = 0; i < len; i++) {
            String str = bufferStr.substring(start, end);
            byte b = Long.valueOf(str, 2).byteValue();
            start += 8;
            end += 8;
            resultArr[i] = b;
        }
        String result = new String(resultArr);
        return result;
    }

    /**
     * 7bit 压缩解压数据
     *
     * @param source
     * @return
     */
    public static String unzip7bitData(String source) {
        byte[] hexArray = ByteUtils.hexString2Bytes(source);
        String binStr = ByteUtils.byteArrToBinStr(hexArray);
        int start = 0;
        int end = 7;
        String temp = "";
        StringBuffer buffer = new StringBuffer();

        int count = source.length() * 4 / 7;
        for (int i = 0; i < count; i++) {
            temp = binStr.substring(start, end);
            start += 7;
            end += 7;

            temp = "0" + temp;
            buffer.append(temp);
        }
        String bufferStr = buffer.toString();
        int len = bufferStr.length() / 8;
        byte[] resultArr = new byte[len];
        start = 0;
        end = 8;
        for (int i = 0; i < len; i++) {
            String str = bufferStr.substring(start, end);
            byte b = Long.valueOf(str, 2).byteValue();
            start += 8;
            end += 8;
            resultArr[i] = b;
        }
        String result = new String(resultArr);
        return result;
    }
}
